import type { InputProps } from 'element-plus'
import { reactive, toRef, toRefs } from 'vue'
import { useRoute } from 'vue-router'

import { roleApi } from '@/apis'
import {
  type GridExtOptions,
  TABLE_FORMAT,
  TABLE_ITEM_RENDER,
  TABLE_RENDERER,
  useGridExt
} from '@/hooks'
import { bus, getElementFnFromInstance } from '@/utils'

import type { AddUserDialogRef } from '../components'

export function useGrid() {
  const state = reactive({
    gridConfig: {
      border: true,
      loading: false,
      align: 'center',
      toolbarConfig: {
        custom: true,
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'userName',
            title: '用户名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'phone',
            title: '手机号',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columns: [
        { type: 'checkbox', width: 50 },
        {
          field: 'userName',
          title: '用户名称'
        },
        {
          field: 'nickName',
          title: '用户昵称'
        },
        {
          field: 'email',
          title: '邮箱'
        },
        {
          field: 'phone',
          title: '手机'
        },
        {
          field: 'status',
          title: '状态',
          width: 100,
          slots: {
            default: 'columns_status'
          }
        },
        {
          field: 'createTime',
          title: '创建时间',
          formatter: TABLE_FORMAT.Date
        },
        {
          title: '操作',
          width: 100,
          className: 'columns_operation',
          slots: {
            default: 'columns_operation'
          }
        }
      ],
      pagerConfig: {
        background: true,
        layouts: [
          'PrevJump',
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ],
        pageSize: 15
      },
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ page, form }) => {
            const data = await roleApi.getAllocatedPage(
              route.params.id as string,
              {
                pageSize: page.pageSize,
                pageNum: page.currentPage,
                ...form
              }
            )
            return data
          }
        }
      },
      onCheckboxChange({ checked, row }) {
        checked
          ? state.selectedIds.add(row.id)
          : state.selectedIds.delete(row.id)
      }
    } as GridExtOptions,
    selectedIds: new Set<string>(),
    addUserDialogRef: {} as AddUserDialogRef
  })

  const route = useRoute()
  const gridExtHook = useGridExt(toRef(state, 'gridConfig'))
  const { $msgbox } = getElementFnFromInstance()

  /**
   * 显示新增
   */
  function handleShowAdd() {
    state.addUserDialogRef.open()
  }

  /**
   * 成功新增
   */
  function handleSuccessAdd() {
    gridExtHook.refresh()
  }

  /**
   * 关闭页面
   */
  function handleClose() {
    bus.emit('handleCloseTab', route)
  }

  /**
   * 批量取消授权
   */
  function handleBatchCancelAuth() {
    $msgbox
      .confirm('确认批量取消授权？', '提示', { type: 'warning' })
      .then(async () => {
        await roleApi.cancelAllocated(route.params.id as string, {
          ids: Array.from(state.selectedIds)
        })

        gridExtHook.refresh()
      })
      .catch(() => {})
  }

  /**
   * 取消授权用户
   */
  function handleCancelAuth(id: string) {
    $msgbox
      .confirm('确认取消授权？', '提示', { type: 'warning' })
      .then(async () => {
        await roleApi.cancelAllocated(route.params.id as string, {
          ids: [id]
        })

        gridExtHook.refresh()
      })
      .catch(() => {})
  }

  return {
    ...toRefs(state),
    gridExtHook,
    handleShowAdd,
    handleSuccessAdd,
    handleClose,
    handleBatchCancelAuth,
    handleCancelAuth
  }
}
